package Service.M.Socket;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import M.ClientAndServer.SimpleMessag;
import Service.M.DB.DataOperator;

public class ATMService extends Thread {
	public static int DEFAULE_PORT = 8008;
	private ServerSocket server = null;

	public ATMService() {
		this(DEFAULE_PORT);
	}

	public ATMService(int port) {
		try {
			server = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			while (true) {
				Socket client = server.accept();
				new ClientThread(client).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	class ClientThread extends Thread {
		private Socket client;
		private ObjectInputStream oin;
		private ObjectOutputStream oop;
		private DataOperator dataOperator;

		public ClientThread(Socket client) {
			try {
				this.client = client;
				oin = new ObjectInputStream(client.getInputStream());
				oop = new ObjectOutputStream(client.getOutputStream());
				this.dataOperator = new DataOperator();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void run() {
			try {
				while (true) {
					SimpleMessag rec = (SimpleMessag) oin.readObject();
					switch (rec.getFunction()) {
					case SimpleMessag.QueryMoney:
						rec.setResult("" + dataOperator.queryMoney(rec.getParam("UserName"), rec.getParam("UserPwd")));
						break;
					case SimpleMessag.UserQuery:
						rec.setResult("" + dataOperator.userQuery(rec.getParam("UserName"), rec.getParam("UserPwd")));
						break;
					case SimpleMessag.UpdateUserMoney:
						rec.setResult("" + dataOperator.updateUserMoney(rec.getParam("UserName"),
								rec.getParam("UserPwd"), Double.parseDouble(rec.getParam("money"))));
						break;
					case SimpleMessag.UpdateUserPassWord:
						rec.setResult("" + dataOperator.updateUserPassWord(rec.getParam("UserName"),
								rec.getParam("UserPwd"), (rec.getParam("newPwd"))));
						break;
					case SimpleMessag.Disconnect:
						rec.setResult("");
						break;
					case SimpleMessag.UNKNOW:
						break;
					default:
						break;
					}
					oop.writeObject(rec.getResult());
					if (SimpleMessag.Disconnect == rec.getFunction()) {
						close();
						break;
					}
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		private void close() {
			try {
				dataOperator.disconnect();
				oin.close();
				oop.close();
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		new ATMService().start();
	}
}
